package com.aster.common.api.wechat.task;

import com.aster.common.api.controller.WechatEscortIndexController;
import com.aster.common.api.wechat.domain.AccessToken;
import com.aster.common.api.wechat.domain.JsTicket;
import com.aster.common.api.wechat.domain.WeChatContent;
import com.aster.common.api.wechat.domain.WeChatFinalValue;
import com.aster.common.api.wechat.util.WXPayUtil;
import com.aster.common.utils.HttpClientUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class RefreshAccessTokenTask {

    private final static Logger log = Logger.getLogger(WechatEscortIndexController.class);

    private String wechat_appid = WXPayUtil.appId;

    private String wechat_appsecret = WXPayUtil.appsecret;

    private String wechat_token="wctest";

    private String wechat_base_url = "";

    @Scheduled(fixedRate = 3600000)
    public void refreshToken() {
        WeChatContent weChatConten=WeChatContent.getInstance();
        weChatConten.setAppId(wechat_appid);
        weChatConten.setAppSecurt(wechat_appsecret);
        weChatConten.setToken(wechat_token);
        weChatConten.setBaseUrl(wechat_base_url);
        String url = WeChatFinalValue.ACCESS_TOKEN_URL;
        url = url.replaceAll("APPID", wechat_appid);
        url = url.replaceAll("APPSECRET", wechat_appsecret);
        try {
            log.info("每隔一小时，主动刷新微信token。。。。。。"+ new Date());
            String content = HttpClientUtil.doGet(url);
            log.info("获取微信token:"+content);
            GsonBuilder gb = new GsonBuilder();
            Gson g = gb.create();
            AccessToken token = g.fromJson(content, AccessToken.class);
            weChatConten.setAccessToken(token);
            weChatConten.setAccessToken(token);
            if(token.getAccess_token() != null && token.getExpires_in() != null){
                String jsUrl = WeChatFinalValue.ACCESS_JS_TOKEN_URL;
                jsUrl = jsUrl.replace("ACCESS_TOKEN", WeChatContent.getInstance().getAccessToken().getAccess_token());
                String jsContent = HttpClientUtil.doGet(jsUrl);
                JsTicket jsToken = g.fromJson(jsContent, JsTicket.class);
                weChatConten.setJsTicket(jsToken);
                log.info("同时获取微信js-token:"+jsContent);
            }
        } catch (Exception ex) {
            log.error("获取微信token出错"+ new Date());
        }
    }
}
